<template>
  <el-form
    v-show="getShow"
    ref="resetFormRef"
    :model="resetData"
    :rules="resetRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row class="mx-[-10px]">
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <LoginFormTitle class="w-full" />
        </el-form-item>
      </el-col>
      <!-- 手机号 -->
      <el-col :span="24" class="px-10px">
        <el-form-item prop="mobile">
          <el-input
            v-model="resetData.mobile"
            :placeholder="t('login.mobileNumberPlaceholder')"
            :prefix-icon="iconCellphone"
            type="number"
            @input="handleMobileInput"
            class="no-spinner"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item prop="smsCode">
          <el-input
            v-model="resetData.smsCode"
            :placeholder="t('login.codePlaceholder')"
            :prefix-icon="iconCircleCheck"
            type="number"
            @input="handleSmsCodeInput"
            class="no-spinner"
          >
            <template #append>
              <span v-if="smsCodeTimer <= 0" class="getSmsCode cursor-pointer" @click="getSmsCode">
                {{ t('login.getSmsCode') }}
              </span>
              <span v-else class="getSmsCode">
                {{ smsCodeTimer }}{{ t('login.getSmsCodeLaterAgain') }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item prop="password">
          <InputPassword
            v-model="resetData.password"
            :placeholder="t('login.passwordPlaceholder')"
            style="width: 100%"
            strength="true"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item prop="confirmPassword">
          <InputPassword
            v-model="resetData.confirmPassword"
            :placeholder="t('login.checkPassword')"
            style="width: 100%"
            strength="true"
          />
        </el-form-item>
      </el-col>
      <!-- 登录按钮 / 返回按钮 -->
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <XButton
            :loading="formLoading"
            :title="t('login.resetPassword')"
            class="w-[100%]"
            type="primary"
            @click="resetPassword()"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <XButton :title="t('login.backLogin')" class="w-[100%]" @click="handleBackLogin()" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { LoginStateEnum, useLoginState } from './useLogin'
import LoginFormTitle from '@/views/base/login/components/LoginFormTitle.vue'
import * as LoginApi from '@/api/base/login'
import { SystemSmsSceneEnum } from '@/utils/constants'

defineOptions({ name: 'ResetPasswdForm' })

const { t } = useI18n()
const message = useMessage()
const resetFormRef = ref()
const formLoading = ref(false)
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { handleBackLogin, getLoginState, setLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.RESET_PASSWD)

const resetDataObj = {
  mobile: '',
  smsCode: '',
  password: '',
  confirmPassword: ''
}
const resetData = ref({ ...resetDataObj })

const validatePass2 = (_rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetData.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const resetRules = {
  mobile: [{ required: true, min: 11, max: 11, trigger: 'blur', message: '手机号长度为11位' }],
  password: [
    {
      required: true,
      min: 4,
      max: 16,
      validator: validatePass2,
      trigger: 'blur',
      message: '密码长度为4到16位'
    }
  ],
  confirmPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }],
  code: [required]
}

const resetPassword = async () => {
  formLoading.value = true
  try {
    if (await formValidate(resetFormRef)) {
      return
    }
    await LoginApi.resetPassword(resetData.value)
    message.success(t('login.resetPasswordSuccess'))
    setLoginState(LoginStateEnum.PASSWD_LOGIN)
    resetData.value = { ...resetDataObj }
  } catch (e) {
  } finally {
    formLoading.value = false
  }
}

const smsCodeTimer = ref(0)
let timerInterval: any = undefined
const getSmsCode = async () => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
  await LoginApi.sendSmsCode({
    mobile: resetData.value.mobile,
    scene: SystemSmsSceneEnum.Staff_Reset_Passwd
  })
  message.success(t('login.smsCodeSendMsg'))
  // 设置倒计时
  smsCodeTimer.value = 60
  timerInterval = setInterval(() => {
    smsCodeTimer.value = smsCodeTimer.value - 1
    if (smsCodeTimer.value <= 0) {
      clearInterval(timerInterval)
    }
  }, 1000)
}

const handleMobileInput = (value: string) => {
  resetData.value.mobile = value.slice(0, 11)
}

const handleSmsCodeInput = (value: string) => {
  resetData.value.smsCode = value.slice(0, 4)
}
</script>

<style scoped lang="scss"></style>
